package iot.core.springboot;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Classname MyFilter
 * @Description 过滤器
 * @Date 2022/3/6 21:47
 * @Created ben
 */
@Component
@Slf4j
@WebFilter(filterName = "MyFilter",
        /**
         * 通配符（*）表示对所有的web资源进行拦截
        */
        urlPatterns = "*"
)
public class MyFilter implements Filter {
    /**
     * 过滤器初始化
     * explain:在容器中创建当前过滤器的时候自动调用
     *
     * @param filterConfig
     */
    @Override
    public void init(FilterConfig filterConfig){
        System.out.println("初始化过滤器!");
    }

    /**
     * 过滤器过滤操作
     * explain:过滤的具体操作
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;






        String url=request.getRequestURI().toString().toLowerCase();
        if(url.startsWith("/swagger")||url.startsWith("/v3")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }


        {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Methods",
                    "POST, GET, OPTIONS, DELETE");
            httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
            httpServletResponse.setHeader("Access-Control-Allow-Headers",
                    "Content-Type, x-requested-with, X-Custom-Header, Authorization,token");
        }

        // 如果是OPTIONS则结束请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.OK.value());
            return;
        }

        log.info("请求地址:"+request.getRequestURI());




        try {
            filterChain.doFilter(servletRequest,servletResponse);

        }
        catch (Exception ex){
            ex.printStackTrace();
        }
        log.info("doFilter end");
    }

    /**
     * 过滤器销毁
     * explain:在容器中销毁当前过滤器的时候自动调用
     */
    @Override
    public void destroy() {
        System.out.println("销毁过滤器!");
    }



}
